function setCookie(key, value, seconds){
    var date = new Date()
    date.setTime(date.getTime()+seconds*1000-8*3600*1000)
    document.cookie = key + '='+value+';expires='+date
}

// 表单校验 - 只需要验证用户名密码不为空即可
$('.logForm').validate({
    rules: {
        username: 'required',
        password: 'required'
    },
    messages: {
        username: '用户名必填',
        password: '密码必填'
    },
    submitHandler(form){
        var loadId = layer.load(2, {
            shade: [1, '#000']
        })
        $('.but').prop('disabled', true)
        $.post('http://localhost:8888/users/login', $(form).serialize()).then(res => {
            // 加载层取消
            console.log(res);
            layer.close(loadId)
            // 判断是否登录成功
            if(res.code === 1){
                layer.msg(res.message, {
                    icon: 1,
                    time: 1500
                }, function(){
                    // 存储cookie
                    setCookie('username', res.user.username, 3600)
                    setCookie('userId', res.user.id, 3600)
                    // 存储token
                    localStorage.setItem('token', res.token)
                    // 跳转
                    // 获取是否有需要跳转的目标页面
                    var reg = /callback=(.+)/
                    var arr = location.search.match(reg)
                    if(arr && arr[1]){
                        location.href = arr[1]
                    }else{
                        location.href = 'index.html'
                    }
                    
                })
            }else{
                layer.msg(res.message, {
                    icon: 2,
                    time: 2000
                }, function(){
                    $('.but').prop('disabled', false)
                })
            }
            console.log(res);
        })
    }
})